<?php
/**
 * Created by PhpStorm.
 * User: jwb
 * Date: 2020/9/23
 * Time: 14:44
 */

namespace App\Inventor\Extensions\Grids\Displayers\Actions;

use Encore\Admin\Admin;
use Encore\Admin\Grid\Displayers\Actions;

class Delete
{
    protected $actions;
    protected $trans = [];

    public function __construct(Actions $actions)
    {
        $this->actions = $actions;
    }

    protected function script()
    {
        $trans = [
            'delete_confirm' => trans('admin.delete_confirm'),
            'confirm'        => trans('admin.confirm'),
            'cancel'         => trans('admin.cancel'),
        ];

        $trans = array_merge($trans, $this->trans);

        return  <<<SCRIPT

$('.grid-row-delete').unbind('click').click(function() {

    var id = $(this).data('id');

    swal({
        title: "{$trans['delete_confirm']}",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "{$trans['confirm']}",
        showLoaderOnConfirm: true,
        cancelButtonText: "{$trans['cancel']}",
        preConfirm: function() {
            return new Promise(function(resolve) {
                $.ajax({
                    method: 'post',
                    url: '{$this->actions->getResource()}/' + id,
                    data: {
                        _method:'delete',
                        _token:LA.token,
                    },
                    success: function (data) {
                        $.pjax.reload('#pjax-container');

                        resolve(data);
                    }
                });
            });
        }
    }).then(function(result) {
        var data = result.value;
        if (typeof data === 'object') {
            if (data.status) {
                swal(data.message, '', 'success');
            } else {
                swal(data.message, '', 'error');
            }
        }
    });
});

SCRIPT;

    }

    protected function render()
    {
        Admin::script($this->script());

        return <<<HTML
<a href="javascript:void(0);" data-id="{$this->actions->getKey()}" class="grid-row-delete">删除</a>
HTML;
    }

    public function __toString()
    {
        return $this->render();
    }

    /**
     * diy delete translate.
     *
     * @param $tans
     */
    public function setTrans($tans)
    {
        $this->trans = $tans;
    }

}